﻿using BCGM.MedicalWisdom.Model.Models;
using BCGM.MedicalWisdom.Services.BASE;
//using BCGM.MedicalWisdom.IRepository.Base;
using System.Collections.Generic;
using System.Threading.Tasks;
using BCGM.MedicalWisdom.Model;
using System.Linq;
using System;
using AutoMapper;
using BCGM.MedicalWisdom.Common;
using System.Linq.Expressions;

using BCGM.MedicalWisdom.Repository.BASE;
using BCGM.MedicalWisdom.IServices.SecondKill;
using BCGM.MedicalWisdom.Model.Models.Patients;
using BCGM.MedicalWisdom.Model.Models.SecondKill;
using BCGM.MedicalWisdom.Model.ViewModels.SecondKillDTO;

namespace BCGM.MedicalWisdom.Services.SecondKill
{
    public class SckillIdActivityServices : BaseServices<SckillIdActivity>, ISckillIdActivityServices
    {
        private readonly IBaseRepository<SckillIdActivity> _dal;
        private readonly IBaseRepository<pharmaceuticalsfen> _pharmaceuticalsfen;
        private readonly IBaseRepository<GoodsDTO> _GoodsDTO;
        private readonly IBaseRepository<Drug> _Drug;
        private readonly IBaseRepository<SckillIdGoods> _sckillIdGoods;
        private readonly IBaseRepository<SeckillGoodMessage> _seckillGoodMessage;
        private readonly IMapper _mapper;   //AutoMapper接口需要依赖注入
        private readonly IRedisCacheManager _redisCacheManager;


        public SckillIdActivityServices(IBaseRepository<SckillIdActivity> dal
            , IBaseRepository<GoodsDTO> goodsDTO
            , IBaseRepository<pharmaceuticalsfen> pharmaceuticalsfen
            , IBaseRepository<Drug> drug, IMapper mapper
            , IBaseRepository<SckillIdGoods> sckillIdGoods
            , IBaseRepository<SeckillGoodMessage> seckillGoodMessage
            , IRedisCacheManager redisCacheManager)
        {
            _dal = dal;
            BaseDal = dal;
            _GoodsDTO = goodsDTO;
            _pharmaceuticalsfen = pharmaceuticalsfen;
            _Drug = drug;
            _mapper = mapper;
            _sckillIdGoods = sckillIdGoods;
            _seckillGoodMessage = seckillGoodMessage;
            _redisCacheManager = redisCacheManager;
        }
        /// <summary>
        /// 非秒杀商品列表
        /// </summary>
        public async Task<PageModel<GoodsDTO>> GetnoSckillGoods(int Sid, string goodsName, int classifyId, int pageIndex, int pageSize)
        {
            string sql = $"SELECT a.DrugId,a.DrugName,a.DrugFacts,a.DrugSkuId,a.DrugImg,a.classifyId FROM Drug AS a WHERE a.DrugId not in (SELECT b.GoodsId from SckillIdGoods AS b where b.Seckillid = {Sid}) and a.IsDeleted = 0";
            string totalSql = $"SELECT a.DrugId,a.DrugName,a.DrugFacts,a.DrugSkuId,a.DrugImg,a.classifyId FROM Drug AS a WHERE a.DrugId not in (SELECT b.GoodsId from SckillIdGoods AS b where b.Seckillid = {Sid}) and a.IsDeleted = 0";
            if (!string.IsNullOrEmpty(goodsName))
            {
                sql = sql + $" and a.DrugName like '%{goodsName}%'";
            }
            if (classifyId != -1)
            {
                sql = sql + $" and a.classifyId={classifyId}";
            }
            sql = sql + $" limit {(pageIndex - 1) * pageSize},{pageSize}";
            List<GoodsDTO> goodsInfoDTOs = await _GoodsDTO.QuerySql(sql);
            List<GoodsDTO> goodstotalSql = await _GoodsDTO.QuerySql(totalSql);

            int total = goodstotalSql.Count();
            return new PageModel<GoodsDTO>()
            {
                data = goodsInfoDTOs,
                dataCount = total
            };
        }
        //商品类型绑定下拉
        public async Task<List<pharmaceuticalsfen>> GetGoodType()
        {
            return await _pharmaceuticalsfen.Query();
        }

        /// <summary>
        /// 添加秒杀活动商品
        /// </summary>
        /// <param name="sckillGoodsIds"></param>
        /// <returns></returns>
        [UseTran]
        public async Task<int> AddSckillGoods(SckillGoodsDTO sckillGoodsIds)
        {
            string[] GoodIds = sckillGoodsIds.GoodsIds.Split(',');
            List<SckillGoodsAddDTO> sckillGoodsAddDTO = new List<SckillGoodsAddDTO>();
            List<SckillIdGoods> sckillIdGoods = new List<SckillIdGoods>();
            List<Drug> drugs = await _Drug.Query();
            foreach (string GoodId in GoodIds)
            {
                Drug drug = drugs.Where(s => s.DrugId == Convert.ToInt32(GoodId)).FirstOrDefault();
                sckillIdGoods.Add(new()
                {
                    Seckillid = sckillGoodsIds.SckillId,
                    GoodsId = Convert.ToInt32(GoodId)
                });
                sckillGoodsAddDTO.Add(new()
                {
                    Spuid = 1,
                    Skuid = drug.DrugSkuId,
                    GoodsId = drug.DrugId,
                    Title = drug.DrugName,
                    ShopPhoto = drug.DrugImg,
                    Price = 1,
                    CostPrice = 0,
                    CreateTime = DateTime.Now,
                    CheckTime = DateTime.Now,
                    GoodStatus = 0,
                    StartTime = DateTime.Now,
                    Endime = DateTime.Now,
                    Num = 1,
                    Stock = drug.Stock,
                    Describes = drug.DrugFacts
                });
            }
            SeckillGoodMessage seckillGoodMessage = _mapper.Map<SeckillGoodMessage>(sckillGoodsAddDTO);
            if (await _seckillGoodMessage.Add(seckillGoodMessage) > 0)
            {
                return await _sckillIdGoods.Add(sckillIdGoods);
            }
            else
            {
                return -1;
            }

        }

        /// <summary>
        /// 获取待预热的秒杀活动商品信息
        /// </summary>
        /// <returns></returns>
        public async Task<List<SeckillGoodMessage>> GetSeckillGoods(int seckillId)
        {
            Expression<Func<SeckillGoodMessage, bool>> whereExpression = a => a.GoodStatus == 1 && a.SeckillId == seckillId;

            return await _seckillGoodMessage.Query(whereExpression);
        }


        /// <summary>
        /// 获取秒杀商品列表（根据审批状态分类）
        /// </summary>
        /// <param name="goodStatus"></param>
        /// <param name="page"></param>
        /// <param name="intPageSize"></param>
        /// <returns></returns>
        public async Task<PageModel<SeckillGoodMessage>> GetSckillGoods(int goodStatus = -1, int page = 1, int intPageSize = 50)
        {
            Expression<Func<SeckillGoodMessage, bool>> whereExpression = a => true;
            if (goodStatus != -1)
            {
                whereExpression = a => a.GoodStatus == goodStatus;
                return await _seckillGoodMessage.QueryPage(whereExpression, page, intPageSize);
            }
            return await _seckillGoodMessage.QueryPage(whereExpression, page, intPageSize);

        }

        //public async Task<MessageModel<PageModel<SeckillGoodMessage>>> GetSckillGoods(int page = 1, int intPageSize = 50)
        //{

        //}
    }
}